package repositories

import (
	"blog-backend/internal/app/models"
	"blog-backend/pkg/database"
)

type CategoryRepository struct{}

func NewCategoryRepository() *CategoryRepository {
	return &CategoryRepository{}
}

// Create 创建分类
func (r *CategoryRepository) Create(category *models.Category) error {
	return database.DB.Create(category).Error
}

// Update 更新分类
func (r *CategoryRepository) Update(category *models.Category) error {
	return database.DB.Save(category).Error
}

// Delete 删除分类
func (r *CategoryRepository) Delete(id uint) error {
	return database.DB.Delete(&models.Category{}, id).Error
}

// GetByID 通过ID获取分类
func (r *CategoryRepository) GetByID(id uint) (*models.Category, error) {
	var category models.Category
	result := database.DB.First(&category, id)
	if result.Error != nil {
		return nil, result.Error
	}
	return &category, nil
}

// GetBySlug 通过Slug获取分类
func (r *CategoryRepository) GetBySlug(slug string) (*models.Category, error) {
	var category models.Category
	result := database.DB.Where("slug = ?", slug).First(&category)
	if result.Error != nil {
		return nil, result.Error
	}
	return &category, nil
}

// GetAll 获取所有分类
func (r *CategoryRepository) GetAll() ([]models.Category, error) {
	var categories []models.Category
	result := database.DB.Find(&categories)
	return categories, result.Error
}

// NameExists 检查分类名称是否存在
func (r *CategoryRepository) NameExists(name string) bool {
	var count int64
	database.DB.Model(&models.Category{}).Where("name = ?", name).Count(&count)
	return count > 0
}

// Exists 检查分类是否存在
func (r *CategoryRepository) Exists(id uint) bool {
	var count int64
	database.DB.Model(&models.Category{}).Where("id = ?", id).Count(&count)
	return count > 0
}

// HasPosts 检查分类下是否有文章
func (r *CategoryRepository) HasPosts(id uint) bool {
	var count int64
	database.DB.Model(&models.Post{}).Where("category_id = ?", id).Count(&count)
	return count > 0
}

// GetPopularCategories 获取热门分类（按文章数量排序）
func (r *CategoryRepository) GetPopularCategories(limit int) ([]models.Category, error) {
	var categories []models.Category
	result := database.DB.Model(&models.Category{}).
		Select("categories.*, COUNT(posts.id) as count").
		Joins("LEFT JOIN posts ON posts.category_id = categories.id").
		Group("categories.id").
		Order("count DESC").
		Limit(limit).
		Find(&categories)
	return categories, result.Error
}
